package jaux.tank.admin.modular.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import jaux.tank.admin.core.base.controller.BaseController;
import jaux.tank.bean.annotion.core.BussinessLog;
import jaux.tank.bean.constant.factory.PageFactory;
import jaux.tank.bean.core.ShiroUser;
import jaux.tank.bean.dictmap.NoticeMap;
import jaux.tank.bean.dto.NoticeDto;
import jaux.tank.bean.entity.system.Notice;
import jaux.tank.bean.enumeration.BizExceptionEnum;
import jaux.tank.bean.exception.TankException;
import jaux.tank.bean.vo.EntityQueryCondition;
import jaux.tank.dao.enums.EntityQueryParamType;
import jaux.tank.dao.system.SysNoticeRepository;
import jaux.tank.dao.utils.JpaUtils;
import jaux.tank.service.system.LogObjectHolder;
import jaux.tank.service.system.NoticeService;
import jaux.tank.service.system.impl.ConstantFactory;
import jaux.tank.shiro.ShiroKit;
import jaux.tank.utils.BeanUtil;
import jaux.tank.utils.StringUtils;
import jaux.tank.utils.ToolUtil;
import jaux.tank.utils.factory.Page;
import jaux.tank.warpper.NoticeWrapper;

/**
 * 通知控制器
 *
 * @Date 2017-05-09 23:02:21
 */
@Controller
@RequestMapping("/notice")
public class NoticeController extends BaseController {

    private static final String PREFIX = "/system/notice/";

    private final SysNoticeRepository sysNoticeRepository;
    
    private final NoticeService noticeService;
	
	public NoticeController(NoticeService noticeService, SysNoticeRepository sysNoticeRepository) {
		this.noticeService = noticeService;
		this.sysNoticeRepository = sysNoticeRepository;
	}



    /**
     * 跳转到通知列表首页
     */
    @GetMapping("")
    public String index() {
        return PREFIX + "notice.html";
    }

    /**
     * 跳转到添加通知
     */
    @GetMapping("/notice_add")
    public String noticeAdd() {
        return PREFIX + "notice_add.html";
    }

    /**
     * 跳转到修改通知
     */
    @GetMapping("/notice_update/{noticeId}")
    public String noticeUpdate(@PathVariable String noticeId, Model model) {
        sysNoticeRepository.findById(noticeId).ifPresent(notice->{
        	model.addAttribute("notice",notice);
        	LogObjectHolder.me().set(notice);
        	
        });
        return PREFIX + "notice_edit.html";
    }

    /**
     * 跳转到首页通知
     */
    @GetMapping("/hello")
    public String hello() {
    	ShiroUser shiroUser = ShiroKit.getUser().orElse(null);
    	if(shiroUser != null) {
	    	
    		Page<Notice> notices = noticeService.queryUserNotices(ShiroKit.getUser().get().getId(), PageFactory.getRequestPage());
    		super.setAttr("noticeList",notices.getRecords());
    	}
        return "/blackboard.html";
    }

    /**
     * 获取通知列表
     */
    @GetMapping("/list")
    @ResponseBody
    public Object list(String condition) {
        List<Notice> list = null;
        if(StringUtils.isNullOrEmpty(condition) || ShiroKit.isAdmin()) {
        	list = this.sysNoticeRepository.findAll();
        }else{
        	List<EntityQueryCondition> conditions = new ArrayList<>();
        	conditions.add(new EntityQueryCondition("title", EntityQueryParamType.LIKE ,condition));
        	ShiroKit.getUser().ifPresent(user->{
        		conditions.add(new EntityQueryCondition("creater", ShiroKit.getUser().get().getId()));
        		
        	});
            list = sysNoticeRepository.findAll(JpaUtils.genPredicateByConditions(
            		conditions
            		, Notice.class));
        }
        return super.warpObject(new NoticeWrapper(BeanUtil.objectsToMaps(list)));
    }

    /**
     * 新增通知
     */
    @PostMapping("/add")
    @BussinessLog(value = "新增通知",key = "title",dict = NoticeMap.class)
    @ResponseBody
    public Object add(NoticeDto notice) {
        if (ToolUtil.isOneEmpty(notice, notice.getTitle(), notice.getContent())) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        Optional<ShiroUser> user = ShiroKit.getUser();
		notice.setCreater(user.isPresent()?user.get().getId():"");
        notice.setCreatetime(new Date());
        Notice noticeInst = new Notice();
		BeanUtils.copyProperties(notice, noticeInst);
       sysNoticeRepository.save(noticeInst);
        return SUCCESS_TIP;
    }

    /**
     * 删除通知
     */
    @DeleteMapping("/delete")
    @ResponseBody
    @BussinessLog(value = "删除通知",key = "noticeId",dict = NoticeMap.class)
    public Object delete(@RequestParam String noticeId) {

        //缓存通知名称
        LogObjectHolder.me().set(ConstantFactory.me().getNoticeTitle(noticeId));

        this.sysNoticeRepository.deleteById(noticeId);

        return SUCCESS_TIP;
    }

    /**
     * 修改通知
     */
    @PutMapping("/update")
    @ResponseBody
    @BussinessLog(value = "修改通知",key = "title",dict = NoticeMap.class)
    public Object update(NoticeDto notice) {
        if (ToolUtil.isOneEmpty(notice, notice.getId(), notice.getTitle(), notice.getContent())) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        noticeService.updateNotice(notice);

		//删除缓存
		LogObjectHolder.me().set(ConstantFactory.me().getNoticeTitle(notice.getId()));
        return SUCCESS_TIP;
    }

}
